<script setup>
import {computed, onMounted, reactive, ref, watch} from "vue"
import { add, edit, deleteById, allTree } from '@/api/system/organization.js'
import {ElMessageBox} from "element-plus";
import { selectList as sysUserSelectList} from '@/api/system/sysUser.js'
import SysUserSelector from "@/components/system/sys-user-selector.vue";

defineOptions({
  name: '/system/organization'
})

//搜索
const search = ref({
  name: "",
  status: ""
})

const sysUserSelectorVisible = ref(false)

//状态枚举
const statusEnums = ref([
  {label: '启用', value: 1},
  {label: '停用', value: 2},
])

//Dialog配置
const dialogConfig = ref({
  visible: false,
  title: "添加",
  closeOnClickModal: false,
  disabled: false
})

//组织实体
const org = ref({
  id: "",
  pid: "",
  name: "",
  status: 1,
  managerId: "",
  managerName: '',
  sort: '',
  introduction: '',
  createTime: "",
  updateTime: ""
})

//组织列表
let orgData = ref([])

//管理用户下拉列表
const sysUserSelectData = ref([
  {id: 1, nickname: '测试1'},
  {id: 2, nickname: '测试2'},
  {id: 3, nickname: '测试3'},
  {id: 4, nickname: '测试4'},
  {id: 5, nickname: '测试5'},
])

//请求全部列表
const requestAllTree = (pid = 0) => {
  allTree().then((resp) => {
    orgData.value = resp.data
  })
}

/**
 * 监听添加事件
 */
const onAdd = () => {
  dialogConfig.value.disabled = false
  dialogConfig.value.visible = true
  dialogConfig.value.title = "添加"
}

//添加子组织
const handleSubAdd = (rowData) => {
  org.value.pid = rowData.id
  dialogConfig.value.disabled = true
  dialogConfig.value.visible = true
  dialogConfig.value.title = "添加"
}

//编辑
const handleEdit = (rowData) => {
  org.value = {...rowData.target}
  if (org.value.pid === '0') {
    org.value.pid = ''
  }
  dialogConfig.value.disabled = true
  dialogConfig.value.visible = true
  dialogConfig.value.title = "编辑"
}

//删除
const handleDelete = (rowData) => {
  ElMessageBox.confirm('您确认删除这条数据吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteById(rowData.target.id).then(() => {
      requestAllTree()
    })
  })
}

/**
 * 处理Dialog关闭后的回调事件
 */
const handleDialogClosed = () => {
  org.value = {
    id: "",
    pid: "",
    name: "",
    status: 1,
    managerId: "",
    managerName: '',
    sort: '',
    introduction: '',
    createTime: "",
    updateTime: ""
  }
}

const managerNameInputTags = computed(() => {
  if (org.value.managerName) {
    return [org.value.managerName]
  } else {
    return  []
  }
})

const rules = reactive({
  name: [
    {required: true, message: '组织名称不能为空', trigger: 'blur'}
  ]
})

/**
 * 监听Dialog确认事件
 */
const onDialogConfirm = async () => {
  if (org.value.id) {
    await edit(org.value)
  } else {
    await add(org.value)
  }
  requestAllTree()
  dialogConfig.value.visible = false
}

/**
 * 挂载后初始化工作
 */
onMounted(() => {
  requestAllTree()
})

watch(() => dialogConfig.value.visible, (newVal) => {
  if (newVal) {
    sysUserSelectList().then(resp => {
      sysUserSelectData.value = resp.data
    })
  }
})

const doInputTagClick = () => {
  sysUserSelectorVisible.value = true
}

const doInputTagSelect = (select) => {
  if (select.length >= 1) {
    let selectItem = select[0]
    org.value.managerId = selectItem.id
    org.value.managerName = selectItem.name

    sysUserSelectorVisible.value = false
  }
}

</script>

<template>
  <div class="cb-main-container">
<!--    <div class="search-box cb-common-box">-->
<!--      <el-form inline :model="search" ref="searchFormRef">-->
<!--        <el-form-item prop="name" label="名称">-->
<!--          <el-input v-model="search.name" placeholder="请输入组织名称"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item prop="status" label="状态" style="width:210px">-->
<!--          <el-select v-model="search.status" placeholder="请选择组织状态">-->
<!--            <el-option v-for="(item, index) in statusEnums" :key="index" :label="item.label" :value="item.value" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item>-->
<!--          <el-button :icon="Refresh" @click="onReset">重置</el-button>-->
<!--          <el-button type="primary" :icon="Search" @click="onSearch">搜索</el-button>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--    </div>-->
    <div class="main-box cb-common-box">
      <div>
        <el-button type="primary" icon="Plus" @click="onAdd()">新增</el-button>
      </div>
      <el-table :data="orgData" row-key="id" class="cb-table-box" default-expand-all empty-text="暂无数据" size="large">
        <el-table-column prop="target.name" label="名称" />
        <el-table-column prop="target.introduction" label="简介" show-overflow-tooltip />
        <el-table-column prop="target.managerName" label="负责人" />
        <el-table-column prop="target.status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.target.status === 1 ? 'primary' : 'info'">{{ scope.row.target.status === 1 ? '开启' : '禁用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="target.sort" label="排序" />
        <el-table-column align="right" label="操作" width="230">
          <template #default="scope">
            <el-button link type="primary" @click="handleEdit(scope.row)" icon="Edit">编辑</el-button>
            <el-button link type="primary" @click="handleSubAdd(scope.row)" icon="Plus">新增</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)" icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑区域S -->
    <el-dialog v-model="dialogConfig.visible" :title="dialogConfig.title" width="500" :close-on-click-modal="dialogConfig.closeOnClickModal" @closed="handleDialogClosed">
      <el-form :model="org" label-width="68px" :rules="rules">
        <el-form-item label="所属组织" prop="pid">
          <el-tree-select
              check-strictly
              :disabled="dialogConfig.disabled"
              node-key="id"
              :props="{label: 'name', }"
              placeholder="请选择所属部门，默认顶级部门"
              v-model="org.pid"
              :data="orgData"
              :render-after-expand="false"
          />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="org.name" autocomplete="off" placeholder="请输入部门名称" maxlength="32" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="name">
              <el-input-tag v-model="managerNameInputTags" readonly tag-type="" @click="doInputTagClick"></el-input-tag>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="org.status" placeholder="请选择部门状态">
                <el-option v-for="(item, index) in statusEnums" :label="item.label" :value="item.value" :key="index" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="org.sort" autocomplete="off" maxlength="3" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="简介" prop="sort">
          <el-input type="textarea" v-model="org.introduction" :rows="6" autocomplete="off" show-word-limit maxlength="500" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogConfig.visible = false">取消</el-button>
          <el-button type="primary" @click="onDialogConfirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加/编辑区域E -->

    <!-- 用户选择器S -->
    <sys-user-selector v-model:visible="sysUserSelectorVisible" @select="doInputTagSelect" :selected-ids="[org.managerId]" />
    <!-- 用户选择器E -->
  </div>
</template>

<style scoped lang="scss">
.cb-main-container {
  flex-direction: column;

  .main-box {
    overflow: scroll;
  }
}
</style>
